$(function() {
	//日期插件初始化
	function timeInit() {
		$.datepicker.regional['zh-CN'] = {
			changeMonth: true,
			changeYear: true,
			clearText: '清除',
			clearStatus: '清除已选日期',
			closeText: '关闭',
			closeStatus: '不改变当前选择',
			prevText: '<上月',
			prevStatus: '显示上月',
			prevBigText: '<<',
			prevBigStatus: '显示上一年',
			nextText: '下月>',
			nextStatus: '显示下月',
			nextBigText: '>>',
			nextBigStatus: '显示下一年',
			currentText: '今天',
			currentStatus: '显示本月',
			monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
			monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
			monthStatus: '选择月份',
			yearStatus: '选择年份',
			weekHeader: '周',
			weekStatus: '年内周次',
			dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
			dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
			dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
			dayStatus: '设置 DD 为一周起始',
			dateStatus: '选择 m月 d日, DD',
			dateFormat: 'yy-mm-dd',
			firstDay: 1,
			initStatus: '请选择日期',
			isRTL: false
		};
		$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
	}

	//页面初始化函数
	var userInfo = "";
	var newAddress = "";
	var paymentCategory = "full"; //首次付款方式
	var deliveryMode = ''; //配送方式
	var isInstall = true; //是否安装
	var regPhone = /^[0-9]*$/; //手机号正则验证
	var preAcitivity = null; //预约的促销活动
	var deposit = 0; //定金金额
	function init() {
		userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
//		console.log(userInfo);
		if(userInfo) {
			$('#userName').html("你好，" + userInfo.name);
		} else {
			window.location.href = "../index.html";
		}
		newAddress = JSON.parse(sessionStorage.getItem("newAddress"));
		var edit = getUrlParam('edit'); //检查地址栏中是否有edit字段
		$('#sellCall').val(userInfo.telephone); //填充营业员电话
		$('#orderDate').val(new Date().Format("yyyy-MM-dd hh:mm:ss"));
		$("#deliveryDate").val(showTime(1));//默认第二天
		
		timeInit();
		$('#orderDate').prop("readonly", true).datetimepicker({
			timeText: '时间',
			hourText: '小时',
			minuteText: '分钟',
			secondText: '秒',
			currentText: '现在',
			closeText: '完成',
			showSecond: true, //显示秒  
			timeFormat: 'HH:mm:ss', //格式化时间  
			changeMonth: true,
			dateFormat: "yy-mm-dd",
		});
		$("#deliveryDate").prop("readonly", true).datepicker({
			changeMonth: true,
			dateFormat: "yy-mm-dd",
			onClose: function(selectedDate) {}
		});
//		$('#deliveryDate').prop("readonly", true).datetimepicker({
//			timeText: '时间',
//			hourText: '小时',
//			minuteText: '分钟',
//			secondText: '秒',
//			currentText: '现在',
//			closeText: '完成',
//			showSecond: true, //显示秒  
//			timeFormat: 'HH:mm:ss', //格式化时间  
//			changeMonth: true,
//			dateFormat: "yy-mm-dd",
//		});
		if(newAddress && edit == 'true') {
			console.log(newAddress)
			if(newAddress.paymentCategory == 'full') {
				paymentCategory = 'full';
				$('#paymentCategory').html("全款"); //deposit（定金），full（全款）
			} else {
				paymentCategory = 'deposit';
				deposit = newAddress.depositNum;//初始化定金金额
				$('#paymentCategory').html("定金：" + newAddress.depositNum + "元"); //deposit（定金），full（全款）
				$('#deposit').val(newAddress.depositNum);
				$('#queryActivityBtn').hide(); //选择定金将促销活动禁用
			}
			if(newAddress.deliveryMode == "delivery") {
				newAddress.deliveryMode = "送货";
			} else if(newAddress.deliveryMode == "selfExtract"){
				newAddress.deliveryMode = "自提";
			}else{
				newAddress.deliveryMode = "货运";
			}
			
			if(newAddress.install == true) {
				newAddress.install = "是";
			} else {
				newAddress.install = "否";
			}
			if(newAddress.preActivities && newAddress.preActivities.length>0){
				preAcitivity = newAddress.preActivities;//将修改信息中的预约活动信息保存到要传递的参数中
				
				var showActs = '';
				for(var i=0; i<newAddress.preActivities.length; i++){
					showActs += newAddress.preActivities[i].activityName + "; ";
				}
				$('#queryActivityBtn').html(showActs);
			}
			$('#consignee').val(newAddress.customerName); //收货人姓名
			$('#memberPhone').val(newAddress.customerTelephone); //会员电话
			$('#receiveTelephone').val(newAddress.receiptTelephone); //收货电话
			$('#deliveryAddress').val(newAddress.receiptAddress); //收货地址
			$('#designCall').val(newAddress.designerPhone); //设计师电话
			$('#sellCall').val(newAddress.sellCall); //营业员电话
			$('#orderDate').val(newAddress.orderDate); //订货日期
			
			$('#deliveryMode').val(newAddress.deliveryMode); //配送方式 delivery（送货），selfExtract（自提），freightTransport（货运）
			$('#deliveryDate').val(newAddress.appointmentDeliveryDate), //配送日期
			$('#isInstall').val(newAddress.install); //是否安装
			$('#gift').val(newAddress.gift); //赠品
			$('#coupon').val(newAddress.voucher); //礼券
			$('#remark').val(newAddress.remark); //备份
		}
	}
	init();

	/**
	 * 获取后一天日期
	 * */
	function addByTransDate(dateParameter, num) {
		var translateDate = "",
			dateString = "",
			monthString = "",
			dayString = "";
		translateDate = dateParameter.replace("-", "/").replace("-", "/");
		var newDate = new Date(translateDate);
		newDate = newDate.valueOf();
		newDate = newDate + num * 24 * 60 * 60 * 1000;
		newDate = new Date(newDate);
		//如果月份长度少于2，则前加 0 补位   
		if((newDate.getMonth() + 1).toString().length == 1) {
			monthString = 0 + "" + (newDate.getMonth() + 1).toString();
		} else {
			monthString = (newDate.getMonth() + 1).toString();
		}
		//如果天数长度少于2，则前加 0 补位   
		if(newDate.getDate().toString().length == 1) {
			dayString = 0 + "" + newDate.getDate().toString();
		} else {
			dayString = newDate.getDate().toString();
		}
		dateString = newDate.getFullYear() + "-" + monthString + "-" + dayString;
		return dateString;
	}
	//得到日期  主方法
	function showTime(pdVal) {
		var trans_day = "";
		var cur_date = new Date();
		var cur_year = new Date().Format("yyyy");
		var cur_month = cur_date.getMonth() + 1;
		var real_date = cur_date.getDate();
		cur_month = cur_month > 9 ? cur_month : ("0" + cur_month);
		real_date = real_date > 9 ? real_date : ("0" + real_date);
		eT = cur_year + "-" + cur_month + "-" + real_date;
		if(pdVal == 1) {
			trans_day = addByTransDate(eT, 1);
		}
		//处理
		return trans_day;
	}

	//检查收货人
	function checkConsignee() {
		if($('#consignee').val() == '') {
			layer.msg("请填写收货人");
			return false;
		}
		return true;
	}
	//检查会员电话
	function checkMemberPhone() {
		if($('#memberPhone').val() != '') {
			if(!regPhone.test($('#memberPhone').val())) {
				layer.msg("请检查会员电话号！");
				return false;
			}
		}
		return true;
	}
	//检查收货电话
	function checkReceiveTelephone() {
		if($('#receiveTelephone').val() == '') {
			layer.msg("请填写收货电话");
			return false;
		}
		return true;
	}
	//检查收货地址
	function checkDeliveryAddress() {
		if($('#deliveryAddress').val() == '') {
			layer.msg("请填写收货地址");
			return false;
		}
		return true;
	}
	//检查设计师电话
	function checkDesignTelephone() {
		if($('#designCall').val() != '') {
//			if(!regPhone.test($('#designCall').val())) {
//				layer.msg("请检查设计师电话号！");
//				return false;
//			}
		}
		return true;
	}
	//检查营业员电话
	function checkSellCall() {
		if($('#sellCall').val() != '') {
//			if(!regPhone.test($('#sellCall').val())) {
//				layer.msg("请检查营业员电话号！");
//				return false;
//			}
		}
		return true;
	}
	//检查送货日期
	function checkDeliveryDate() {
		if($('#deliveryDate').val() == '') {
			layer.msg("请填写送货日期！");
			return false;
		}
		return true;
	}
	//获取付款方式
	$('#paymentCategory').click(function() {
		$('#popConfirm').show();
		if(paymentCategory == "full"){
			$('#payFull').prop('checked', true);
			$('.depositInput').hide();//输入框隐藏
		}else{
			$('#payFull').prop('checked', false);
			$('#payDeposit').prop('checked', true);
			$('.depositInput').show();//输入框显示
		}
	})
	$('#payFull').change(function(){
		if($(this).prop('checked') == true){
			$('.depositInput').hide();//隐藏输入框
		}
	})
	$('#payDeposit').change(function(){
		if($(this).prop('checked') == true){
			$('.depositInput').show();//输入框显示
		}
	})
	//定金金额确定窗口
	
	$('.cancleBtn').click(function() {
		$('#popConfirm').hide();
		
	})
	$('.confirmBtn').click(function() {
		if($('#payFull').prop('checked') == true){
			paymentCategory = "full"; //全款关键字
			deposit = 0;//选择全款，定金为0
			$('#paymentCategory').html("全款");
			$('#queryActivityBtn').show(); //选择全款将促销活动解禁
			$('#popConfirm').hide();
			if(!$.isArray(preAcitivity)){
				preAcitivity = [];
			}
		}else if($('#payDeposit').prop('checked') == true){
			deposit = $('#deposit').val(); //输入的定金金额数
			if(deposit == '') {
				layer.msg("请输入定金金额");
			}else if(deposit <= 0){
				layer.msg("您输入的金额不能为：" + deposit);
			}else {
				paymentCategory = "deposit"; //定金关键字
				$('#paymentCategory').html("定金：" + deposit + "元");
				$('#queryActivityBtn').hide(); //选择定金将促销活动禁用
				$('#popConfirm').hide();
				preAcitivity = null;
			}
		}
	})

	//获取配送方式
	function getDeliveryMode() {
		deliveryMode = $('#deliveryMode').val();
		if(deliveryMode == '送货') {
			deliveryMode = "delivery"; //送货关键字
		} else if(deliveryMode == '自提'){
			deliveryMode = "selfExtract"; //自提关键字
		}else{
			deliveryMode = "freightTransport";//货运关键字
		}
	}
	getDeliveryMode(); //初始化配送方式
	$('#deliveryMode').change(function() {
		getDeliveryMode();
	})
	//获取是否安装
	function getIsInstall() {
		isInstall = $('#isInstall').val();
		if(isInstall == "是") {
			isInstall = true;
		} else {
			isInstall = false;
		}
	}
	getIsInstall(); //初始化安装方式
	$('#isInstall').change(function() {
		getIsInstall();
	})

	//查询活动
	
	$('#queryActivityBtn').click(function() {
//		preAcitivity = [];//置为数组
		var postData = {
			filter:{
				contracts: []
			}
		}
		for(var i = 0; i < userInfo.stores[0].contracts.length; i++) {
			postData.filter.contracts.push(userInfo.stores[0].contracts[i].uuid);
		}
		queryActivity(postData, newAddress,preAcitivity);
		$('.popActivity').show();
	});
	//查询活动确定和取消按钮
	$('.confirmAct').click(function() {
		var isSelected = false;

		var selectedActs = '';//选中的活动
		if(preAcitivity && $.isArray(preAcitivity)){
			if(preAcitivity.length>=0){
				preAcitivity.splice(0,preAcitivity.length);//如果预约活动已经存有数据，先清空数组，再添加数据
			}
		}else{
			preAcitivity = [];
		}
		$('.activityItem').each(function() {
			var index = $(this).parent().index();
			if($(this).prop('checked') == true) {
				isSelected = true;
				var item = {
					activityName: util.activityLists[index].activityName,
					promotionUuid: util.activityLists[index].promBillUuid,
				}
				preAcitivity.push(item); //将当前选中的活动存储到数组中
				selectedActs += util.activityLists[index].activityName + '; ';
			}
		});
		
		if(isSelected == false) {
			$('#queryActivityBtn').html("查询活动");
			preAcitivity.splice(0,preAcitivity.length);//如果没有选择活动，清空活动保存数据
			preAcitivity = null;
		} else {
			$('#queryActivityBtn').html(selectedActs);
		}
		$('.popActivity').hide();
	})
	$('.cancelAct').click(function() {
		$('.popActivity').hide();
//		preAcitivity = null;
	})

	$('#submitBtn').click(function() {
		if(checkConsignee() && checkMemberPhone() && checkReceiveTelephone() && checkDeliveryAddress() && checkDesignTelephone() && checkSellCall() && checkDeliveryDate()) {
			if(paymentCategory == 'deposit'){
				preAcitivity = null;
			}
			if($.isArray(preAcitivity) && preAcitivity.length == 0){
				preAcitivity = null;
			}
			var newInfo = JSON.stringify({
				customerName: $('#consignee').val(), //收货人姓名
				customerTelephone: $('#memberPhone').val(), //会员电话
				receiptTelephone: $('#receiveTelephone').val(), //收货电话
				receiptAddress: $('#deliveryAddress').val(), //收货地址
				designerPhone: $('#designCall').val(), //设计师电话
				sellCall: $('#sellCall').val(), //营业员电话
				orderDate: $('#orderDate').val(), //订货日期
				paymentCategory: paymentCategory, //deposit（定金），full（全款）
				preActivities: preAcitivity, //预选促销活动
				deliveryMode: deliveryMode, //配送方式
				appointmentDeliveryDate: $('#deliveryDate').val(), //配送日期
				install: isInstall, //是否安装
				gift: $('#gift').val(), //赠品
				voucher: $('#coupon').val(), //礼券
				remark: $('#remark').val(), //备份
				depositNum: deposit, //定金金额
			})
			layer.confirm('确定提交信息？', {
				btn: ['确定', '取消'] //按钮
			}, function() {
				sessionStorage.setItem("newAddress", newInfo);
				window.location.href = "shopCart.html";
			});
		}
	})
})